package com.supplychain.scm.core.framework.strategy;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.Objects;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName AbstractStrategy
 * @Description 抽象策略定义做底层扩展使用
 * @createTime 14:35:00 2022/10/14
 */
@Slf4j
public abstract class AbstractStrategy<T, R> implements IStrategy<T, R> {
    /**
     * 业务处理之前处理
     *
     * @param t
     * @return
     */
    protected Object beforeHandler(T t) {
        return null;
    }

    /**
     * 策略业务处理方法定义
     *
     * @param t
     * @param beforeResult
     * @return
     */
    protected R handler(T t,Object beforeResult) {
        throw new UnsupportedOperationException();
    }

    /**
     * 业务处理之后处理
     *
     * @param t
     * @param r
     * @return
     */
    protected Object afterHandler(T t, R r) {
        return null;
    }

    /**
     * 异常处理器
     *
     * @param t
     * @return
     */
    protected R exceptionHandler(T t, Throwable e) {
        return null;
    }

    /**
     * 最终处理器
     *
     * @param t
     * @return
     */
    protected Object finallyHandler(T t, R r) {
        return null;
    }

    public R strategyHandler(T t) {
		R handler = null;
        try {
            Object beforeResult = this.beforeHandler(t);
            handler = this.handler(t,beforeResult);
			this.afterHandler(t, handler);
        } catch (Throwable e) {
            handler = this.exceptionHandler(t, e);
            if(Objects.isNull(handler)) {
                log.warn("策略处理器发生异常:{}", ExceptionUtils.getStackTrace(e));
                throw e;
            }
        } finally {
            this.finallyHandler(t, handler);
        }
		return handler;
    }
}
